import React, { useMemo, useState } from 'react'
import { Button } from 'antd-mobile'

function formatShort(dateStr) {
  const d = new Date(dateStr)
  return `${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`
}

export default function ChartSection({ weights }) {
  const [chartType, setChartType] = useState('line')

  const sorted = useMemo(() => weights.slice().sort((a,b)=>new Date(a.date)-new Date(b.date)), [weights])

  const stats = useMemo(()=>{
    if (sorted.length === 0) return { min:0,max:0,avg:0,current:0,trend:0 }
    const byWeight = [...sorted].sort((a,b)=>a.weight-b.weight)
    const sum = sorted.reduce((s,w)=>s+w.weight,0)
    const current = sorted[sorted.length-1].weight
    const earliest = sorted[0].weight
    return { min: byWeight[0].weight, max: byWeight[byWeight.length-1].weight, avg: sum/sorted.length, current, trend: current - earliest }
  },[sorted])

  const width = 720
  const height = 300
  const padding = 36

  const points = useMemo(()=>{
    if (sorted.length === 0) return []
    const weightsArr = sorted.map(s=>s.weight)
    const min = Math.min(...weightsArr)
    const max = Math.max(...weightsArr)
    const range = max - min || 1
    const stepX = (width - padding*2) / Math.max(1, sorted.length - 1)
    return sorted.map((d,i)=>{
      const x = padding + i * stepX
      const y = padding + (1 - (d.weight - min)/range) * (height - padding*2)
      return { x, y, label: formatShort(d.date), weight: d.weight }
    })
  },[sorted])

  const polyPoints = points.map(p=>`${p.x},${p.y}`).join(' ')

  return (
    <div>
      <div style={{display:'flex', gap:8, marginBottom:12}}>
        <div style={{flex:1}}>
          <div style={{fontSize:12}}>最低</div>
          <div style={{fontWeight:700}}>{stats.min.toFixed(1)}</div>
        </div>
        <div style={{flex:1}}>
          <div style={{fontSize:12}}>最高</div>
          <div style={{fontWeight:700}}>{stats.max.toFixed(1)}</div>
        </div>
        <div style={{flex:1}}>
          <div style={{fontSize:12}}>平均</div>
          <div style={{fontWeight:700}}>{stats.avg.toFixed(1)}</div>
        </div>
      </div>

      <div style={{background:'#fff', padding:12, borderRadius:8}}>
        <div style={{display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:12}}>
          <h4 style={{margin:0}}>体重趋势图</h4>
          <div style={{display:'flex', gap:8}}>
            <Button onClick={()=>setChartType('line')}>折线</Button>
            <Button onClick={()=>setChartType('area')}>面积</Button>
          </div>
        </div>

        {points.length === 0 ? (
          <div style={{height:200, display:'flex', alignItems:'center', justifyContent:'center'}}>暂无数据</div>
        ) : (
          <div style={{overflowX:'auto'}}>
            <svg width={Math.max(360, width)} height={height} style={{maxWidth:'100%'}}>
              {/* grid lines */}
              <line x1={padding} x2={width-padding} y1={padding} y2={padding} stroke="#eee" />
              <line x1={padding} x2={width-padding} y1={height-padding} y2={height-padding} stroke="#eee" />

              {/* area fill if chosen */}
              {chartType === 'area' && (
                <polyline points={`${polyPoints} ${width-padding},${height-padding} ${padding},${height-padding}`} fill="#cce6ff" stroke="none" opacity={0.6} />
              )}

              {/* line */}
              <polyline points={polyPoints} fill="none" stroke="#2563eb" strokeWidth={2} />

              {/* points */}
              {points.map((p, i)=>(<circle key={i} cx={p.x} cy={p.y} r={3} fill="#2563eb" />))}

              {/* x labels */}
              {points.map((p,i)=> (
                <text key={i} x={p.x} y={height - 8} fontSize={10} textAnchor="middle" fill="#333">{p.label}</text>
              ))}
            </svg>
          </div>
        )}
      </div>
    </div>
  )
}
